define([ 
        // Libs
        'Zepto',     
        'Underscore', 
        'Backbone',

        //Views
        
        //Collections
        './collection/leggiCollection',
        
        //Templates
        '../js/lib/text!../timeline.html',
        '../js/lib/text!../more.html',
        '../js/lib/text!../newcomment.html',
        
        //Additional libs
        'OAuth',
        'Childbrowser'
        
        ], function( $, _, Backbone, LeggiCollection, TimelineTemplate, MoreTemplate, NewComment ){
       
	   	var AppRouter = Backbone.Router.extend({
	   		
	   										  routes: {
                                            	        "":"home",
                                            	        "timeline":"timeline"	
                                            	    },

                                            	    initialize:function () {
                                            	        
                                            	    	// Handle back button throughout the application
                                            	        $('.back').live('click', function(event) {
                                            	            window.history.back();
                                            	            return false;
                                            	        });
                                            	        this.firstPage = true;

                                            	    },
                                            	    timeline:function () {
                                            	    	var inizio = "201301";
                                            	    	var fine = "201302";
                                            	    	var leggi = new LeggiCollection( "datainizio=" + inizio +"/datafine=" + fine + "/");
                                            	    	leggi.fetch({
                                            	    		success: function(){
                                            	    			$('body').html(_.template(TimelineTemplate, {leggi : leggi, id_utente : leggi.id_utente}));
                                            	    			
                                            	    			$(".submit_post").bind("submit", function() {
                                            	    				var inputs = $(this);	
                                            	    				var id_legge = inputs[0][1].value;
                                            	    				var testo_commento = inputs[0][0].value;
                                            	    				var username = "@" + window.username;
                                            	    				
                                            	    				if(testo_commento != "" && testo_commento){
	                                            	    				$.ajax({
	                                            	    					  type: 'GET',
	                                            	    					  url: 'http://www.govdebate.altervista.org/comment/idlegge=' +
	                                            	    					  		id_legge +'/testo=' + testo_commento + '/user=' + username,
	                                            	    					  // type of data we are expecting in return:
	                                            	    					  dataType: 'json',
	                                            	    					  context: $(".com_row"),
	                                            	    					  success: function(data){
	                                            	    					  	
		                                            	    					    inputs.parent().parent().parent().append(_.template(NewComment , {parlamentare : false, testo : testo_commento, id_utente : username}));
	                                            	    					  }
	                                            	    					});
                                            	    			}
                                            	    					
                                            	    				
                                            	    			});
                                            	    			
                                            	    			$(".feedb_positive").bind("click", function(){
                                            	    				var input = $(this);
                                            	    				input.unbind();
                                            	    				
                                            	    				$.ajax({
                                            	    					type: 'GET',
                                            	    					url: 'http://www.govdebate.altervista.org/feed/flag=1/atto=' + input[0].value + '/utente=@' + window.username,
                                            	    					datatype: 'json',
                                            	    					context: $(".feed_lex"),
                                            	    					success: function(data){
                                            	    						console.log(data);
                                            	    					}
                                            	    				});
                                            	    			});
                                            	    			
                                            	    			$(".feedb_negative").bind("click", function(){
                                            	    				var input = $(this);
                                            	    				input.unbind();
                                            	    				
                                            	    				$.ajax({
                                            	    					type: 'GET',
                                            	    					url: 'http://www.govdebate.altervista.org/feed/flag=0/atto=" +input[0].value" /utente=@' + matteoblasioli,
                                            	    					datatype: 'json',
                                            	    					context: $(".feed_lex"),
                                            	    					success: function(data){
                                            	    						console.log(data);
                                            	    					}
                                            	    				});
                                            	    			});
                                            	    			var carica_altri = $("#loadmore");
                                            	    			carica_altri.bind("click", function() {
                                            	    				carica_altri.html("<img alt=\"Caricamento\" src=\"./img/loading.gif\">");
                                            	    				inizio -= 1;
                                                	    			fine -= 1;
                                                	    			if(("" + inizio).slice(5,6) == 0){
                                                	    				inizio -= 88;
                                                	    			}	
                                                	    			if(("" + fine).slice(5,6) == 0){
                                                	    				fine -= 88;
                                                	    			}
                                                	    			var more = new LeggiCollection( "datainizio=" + inizio +"/datafine=" + fine + "/");
                                                	    			more.fetch({ 
                                                	    				success: function(){
                                                	    					$("#loadhere").html(_.template(MoreTemplate, {leggi : more}));
                                                	    					carica_altri.html("Carica Precedenti");
                                                	    					
                                                	    					$(".submit_post").bind("submit", function() {
                                            	    				var inputs = $(this);
                                            	    				var id_legge = inputs[0][1].value;
                                            	    				var testo_commento = inputs[0][0].value;
                                            	    				var username = "@" + window.username;
                                            	    				
                                            	    				if(testo_commento != "" && testo_commento){
	                                            	    				$.ajax({
	                                            	    					  type: 'GET',
	                                            	    					  url: 'http://www.govdebate.altervista.org/comment/idlegge=' +
	                                            	    					  		id_legge +'/testo=' + testo_commento + '/user=' + username,
	                                            	    					  // type of data we are expecting in return:
	                                            	    					  dataType: 'json',
	                                            	    					  context: $(".com_row"),
	                                            	    					  success: function(data){
	                                            	    					  	
	                                            	    					    inputs.parent().parent().parent().append(_.template(NewComment , {parlamentare : false, testo : testo_commento, id_utente : username}));
	                                            	    					  }
	                                            	    					});
                                            	    			}
                                            	    					
                                            	    				
                                            	    			});
                                            	    			
                                               			$(".feedb_positive").bind("click", function(){
                                            	    				var input = $(this);
                                            	    				input.unbind();
                                            	    				
                                            	    				$.ajax({
                                            	    					type: 'GET',
                                            	    					url: 'http://www.govdebate.altervista.org/feed/flag=1/atto=' + input[0].value + '/utente=@' + window.username,
                                            	    					datatype: 'json',
                                            	    					context: input,
                                            	    					success: function(data){
                                            	    						console.log(data);
                                            	    					}
                                            	    				});
                                            	    			});
                                            	    			
                                            	    			$(".feedb_negative").bind("click", function(){
                                            	    				var input = $(this);
                                            	    				input.unbind();
                                            	    				
                                            	    				$.ajax({
                                            	    					type: 'GET',
                                            	    					url: 'http://www.govdebate.altervista.org/feed/flag=0/atto=" +input[0].value" /utente=@' + matteoblasioli,
                                            	    					datatype: 'json',
                                            	    					context: $(".feed_lex"),
                                            	    					success: function(data){
                                            	    						console.log(data);
                                            	    					}
                                            	    				});
                                            	    			});
                                                	    					
                                                	    				}
                                                	    			});
                                            	    			});
                                            	    		}
                                            	    	});

                                            	    },

                                            	    home:function () {
                                            	    	 var oauth, options, response, that = this;
                                            	    	 options = {
                                             	    	        consumerKey: 'SomETC01QKdFrWLUuUY6Gw',
                                             	    	        consumerSecret: '1XSeFd0LV9SeysMy0x4J5NZ6WfUeSgQmuWSLC3GukeY',
                                             	    	    	callbackUrl: 'http://govdebate.altervista.org/benvenuto.html'	
                                             	    	    };
                                         	    	               
                                            	    	 $("#start").bind('click', function () {
                                            	    		 window.location.hash = "/timeline";
                                            	    		 
                                            	    		 //Monitoriamo il cambio di url del childbrowser
                                            	    		 if (typeof window.plugins.childBrowser.onLocationChange !== "function") {
                                            	    	            window.plugins.childBrowser.onLocationChange = function(loc){
                                            	    	            	loc=decodeURIComponent(loc);
                                            	    	                
                                                           	    	 // The supplied oauth_callback_url for this session is being loaded
                                                                           if (loc.indexOf("http://govdebate.altervista.org/benvenuto.html?") >= 0) {
                                                                               var index, verifier = '';            
                                                                               var params = loc.substr(loc.indexOf('?') + 1);
                                                                               
                                                                               params = params.split('&');
                                                                               for (var i = 0; i < params.length; i++) {
                                                                                   var y = params[i].split('=');
                                                                                   if(y[0] === 'oauth_verifier') {
                                                                                       verifier = y[1];
                                                                                   }
                                                                               }

                                                                             // Exchange request token for access token
                                                                               oauth.get('https://api.twitter.com/oauth/access_token?oauth_verifier='+verifier+'&'+response[0] + '&' + response[1] + '&' + response[2],
                                                                                       function(data) {
                                                                            	   			var accessParams = {};
                                                                            	   			var qvars_tmp = data.text.split('&');
                                                                            	   			for (var i = 0; i < qvars_tmp.length; i++) {
                                                                            	   				var y = qvars_tmp[i].split('=');
                                                                            	   				accessParams[y[0]] = decodeURIComponent(y[1]);
                                                                            	   			}
                                                                            	   			oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);
                                                                            	   			oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
                                                                                                    function(data) {
                                                                                                        var entry = JSON.parse(data.text);
                                                                                                        window.username = entry.screen_name;
                                                                                                        window.plugins.childBrowser.close();
                                                                                                        window.location.hash = "/timeline";
                                                                                                    });
                                                                               });
                                                                           };
                                                                           
                                            	    	            }
                                            	    	    };
                                            	    	    
                                            	    		
                                            	    	    oauth = OAuth(options);
                                            	    	    oauth.get('https://api.twitter.com/oauth/request_token', function (data) {
                                            	    	    response = data.text.split("&");
                                            	    	    if((response[2].split("="))[1]){
                                              	    	        window.plugins.childBrowser.showWebPage('https://api.twitter.com/oauth/authenticate?'+data.text, 
                                                                      { showLocationBar : false }); 
                                            	    	        }
                                            	    	    });
                                            	    	 });    
                                            	    	     
                                            	    },

                                            	    changePage:function (page) {
                                           	  
                                            	    	}

                                            	});
   
       return AppRouter;
       // What we return here will be used by other modules
    });

